package com.longe.controller;

import com.longe.entity.User;
import com.longe.util.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("login")
    public String login(String userName, String password, HttpServletResponse response){

        Subject current = SecurityUtils.getSubject();
        //判断该subject是否认证
        if(!current.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            try {
                current.login(token);
            } catch (UnknownAccountException e) {
                throw new RuntimeException("账号不存在");
            } catch (IncorrectCredentialsException e) {
                throw new RuntimeException("密码不正确");
            } catch (Exception e) {
                throw new RuntimeException("内部错误");
            }
        }

        User user = (User) current.getPrincipal();
        System.err.println("当前用户为：" + user);

        Map<String, Object> mapInfo = new HashMap<>();
        mapInfo.put("info", user);
        String token = jwtUtil.createJWT(user.getId().toString(), user.getUserName(), mapInfo);
        response.setHeader("token", token);

        return "home";
    }

    @RequestMapping("logout")
    public String logout(){

        Subject current = SecurityUtils.getSubject();
        current.logout();

        return "/";
    }

    @RequestMapping("test")
    public String haha(){

        return "home";
    }
}
